package com.sisucc.contractmanage.web.index;

import com.sisucc.contractmanage.bean.accountInfo.AccountInfoBean;
import com.sisucc.contractmanage.bean.staffInfo.StaffInfoBean;
import com.sisucc.contractmanage.constant.ConstantDataType;
import com.sisucc.contractmanage.constant.ReturnStatusCode;
import com.sisucc.contractmanage.dao.accountInfo.AccountInfoRepository;
import com.sisucc.contractmanage.dao.staffInfo.StaffInfoRepository;
import com.sisucc.contractmanage.service.indexService.IndexService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author linyuqi
 */
@Log4j2
@Controller
public class IndexController {

    @Autowired
    private IndexService service;

    @Autowired
    private AccountInfoRepository accountInfoRepository;

    @Autowired
    private StaffInfoRepository staffInfoRepository;

    @RequestMapping({"/", "/index"})
    public String index(HttpSession session) {
        User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        AccountInfoBean accountInfoBean = accountInfoRepository.findByAccountCode(currentUser.getUsername());
        StaffInfoBean staffInfoBean = staffInfoRepository.findById(accountInfoBean.getAccountInfoId()).get();
        session.setAttribute("currentAccountInfo", accountInfoBean);
        session.setAttribute("currentStaffInfo", staffInfoBean);
        String sessionId = session.getId();
        log.info("当前访问网站的sessionId：" + sessionId);
        return "index/index";
    }

    @ResponseBody
    @PostMapping("/getCurrentUser")
    public String getCurrentUser(HttpSession session) {
        StaffInfoBean staffInfo = (StaffInfoBean) session.getAttribute("currentStaffInfo");
        if (!ConstantDataType.ROOT_USER.equals(staffInfo.getStaffCode())) {
            return ReturnStatusCode.SUCCESS_CODE;
        }
        log.info("当前访问网站的用户：" + staffInfo.toString());
        return ReturnStatusCode.ERROR_CODE;
    }

}
